package com.leo.blog.listener;

import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.leo.blog.dto.VisitExecution;
import com.leo.blog.entity.Visit;
import com.leo.blog.enums.VisitStateEnum;
import com.leo.blog.service.VisitService;
import com.leo.blog.util.AddressUtil;
import com.leo.blog.util.UserAgentUtil;
import com.leo.blog.util.UserIpUtil;

@WebListener
public class VisitTimesListener implements ServletRequestListener{
	private Log log = LogFactory.getLog(getClass());
	private ApplicationContext applicationContext = null;
	
	@Override
	public void requestDestroyed(ServletRequestEvent arg0) {

	}
	
	@Override
	public void requestInitialized(ServletRequestEvent arg0) {
		HttpServletRequest request = (HttpServletRequest) arg0.getServletRequest();
		HttpSession session = request.getSession();
		ServletContext servletContext = session.getServletContext();
		Visit visit = null;
		VisitService visitServiceImpl = null;
		applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		try {
			visitServiceImpl = (VisitService) applicationContext.getBean("visitServiceImpl");
			if(session.isNew()) {
				log.debug("-------applicationContext--------");
				log.debug("begin- " + applicationContext + " -end");
				log.debug("-----begin-----");
				log.debug(applicationContext.getBean("visitServiceImpl"));
				
				// 先判断当前ip当天是否已经访问过,如果没有则保存当前访问记录
				visit = new Visit();
				visit.setVisitIp(UserIpUtil.getIp(request));
				visit.setCreateTime(new Date());
				String userAgent = request.getHeader("user-agent");
				visit.setUserAgent(userAgent);
				synchronized (this) {
					VisitExecution ve = visitServiceImpl.getVisitByTimesCount(visit);
					if(ve.getState() == VisitStateEnum.OFFLINE.getState()) {
						visit.setPlatformType(UserAgentUtil.getUserAgent(userAgent).getPlatformType());
						visit.setBrowserType(UserAgentUtil.getUserAgent(userAgent).getBrowserType());
						visit.setUrl(request.getRequestURI().toString());
						visit.setCity(new AddressUtil().getAddresses("ip=" + visit.getVisitIp(), "gbk"));
						visitServiceImpl.addVisit(visit);
					}
				}		
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
}
